package com.forlove.app.qselect.login.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.forlove.app.R;
import com.forlove.app.common.base.ui.BaseTakePhotoActivity;
import com.forlove.app.common.utils.LogUtil;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.common.widget.CircleImageView;
import com.forlove.app.manager.CustomHelper;
import com.forlove.app.manager.NetworkManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.login.entity.UserEntity;
import com.forlove.app.qselect.login.presenter.SetAccountPresenter;
import com.forlove.app.qselect.login.view.SetAccountView;
import com.jph.takephoto.model.CropOptions;
import com.jph.takephoto.model.TResult;

import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;

/**
 * Created by yjl on 2017/10/10.
 */

public class SetAccountActivity extends BaseTakePhotoActivity
        implements View.OnClickListener, SetAccountView {
    @BindView(R.id.view_set_account)
    LinearLayout view_set_account;//设置账号页面

    @BindView(R.id.bt_setaccount_next_step)
    TextView bt_setaccount_next_step; //设置账号的下一步

    @BindView(R.id.editText_input_account)
    AppCompatEditText editText_input_account;//设置账号

    @BindView(R.id.text_input_num)
    TextView text_input_num;  //输入数字数目

    @BindView(R.id.view_set_photo)
    CircleImageView view_set_photo; //设置账户头像

    private SetAccountPresenter setAccountPresenter;
    private String userName = "";
    private String photoPath = "";
    private boolean setAccountResult = false;
    private boolean setPhotoResult = false;
    private UserEntity userEntity;
    private long timeDelt = 0;

    @Override
    public int getLayoutId() {
        return R.layout.activity_set_account;
    }

    @Override
    public void initView() {
        setAccountPresenter = new SetAccountPresenter(this);
        setPresenter(setAccountPresenter);
        bt_setaccount_next_step.setOnClickListener(this);
        view_set_photo.setOnClickListener(this);
        userEntity = UserManager.getUesrInfo(this);
        editText_input_account.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable text) {
                userName = text.toString();

                if (!TextUtils.isEmpty(userName)) {
                    text_input_num.setText((20 - userName.length()) + "");
                    bt_setaccount_next_step.setBackground(getResources().getDrawable(R.drawable.bt_nextstep_selector));
                } else {
                    text_input_num.setText(20 + "");
                    bt_setaccount_next_step.setBackground(getResources().getDrawable(R.drawable.bg_blue_nextstep_corner_sel));
                }
            }
        });

        if (userEntity != null && StringUtils.isNotEmpty(userEntity.userName)) {
            editText_input_account.setText(userEntity.userName);
            setAccountResult = true;//设置用户名后则无法修改用户名，所以不让用户再次修改
            editText_input_account.setEnabled(false);
        }
        if (userEntity != null && !TextUtils.isEmpty(userEntity.mUserImage)) {
            setPhotoResult = true;
            setAccountPresenter.loadImageView(this,
                    view_set_photo, userEntity.mUserImage,
                    R.mipmap.image_mine_friend_avatar);
        }
    }

    private void requestSetAccount() {
        if (TextUtils.isEmpty(userName)
                || !StringUtils.isAccount(userName)) {
            Toast.makeText(this, "请设置唯一用户名,2至20个字母、数字、下划线和减号,必须以字母开头", Toast.LENGTH_SHORT).show();
            return;
        }
        if (UserManager.getUserLoginState(this)) {
            if (userEntity != null) {
                Map param = new HashMap();
                param.put("username", userName);
                setAccountPresenter.loadSetAccountData(param);
            }

        }
    }

    private void requestUplaodeImage() {
        if (TextUtils.isEmpty(photoPath)) {
            return;
        }
        Map param = new HashMap();
        param.put("Filedata", photoPath);
        setAccountPresenter.upLoadPic(param);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_setaccount_next_step:
                if (System.currentTimeMillis() - timeDelt < 2000) {
                    timeDelt = System.currentTimeMillis();
                    return;
                }
                if (!setAccountResult) {
                    requestSetAccount();
                }
                if (!setAccountResult && StringUtils.isNotEmpty(userEntity.userName)) {
                    Toast.makeText(this, "请设置账号", Toast.LENGTH_SHORT).show();
                }

                if (!setPhotoResult) {
                    requestUplaodeImage();
                }
                if (!setPhotoResult && !StringUtils.isNotEmpty(userEntity.mUserImage)
                        && TextUtils.isEmpty(photoPath)) {
                    Toast.makeText(this, "请设置头像", Toast.LENGTH_SHORT).show();
                }
                if (setPhotoResult && setAccountResult) {
                    startActivity(new Intent(this, SetUserInfoActivity.class));
                }
                break;
            case R.id.view_set_photo:
                CropOptions cropOptions = CustomHelper.getCustomHelper().getCropOptions();
                Uri imageUri = CustomHelper.getCustomHelper().getURI(getTakePhoto());//保存的路径
                getTakePhoto().onPickFromDocumentsWithCrop(imageUri, cropOptions);
                break;
        }
    }

    @Override
    public void updateSetAccountView(NetworkManager.ResultCode resultCode, String error) {
        if (NetworkManager.ResultCode.RESULT_SUCCESS.equals(resultCode)) {
            setAccountResult = true;
            Toast.makeText(this, "设置成功!", Toast.LENGTH_SHORT).show();
            userEntity.userName = userName;
            setAccountResult = true;
            editText_input_account.setText(userName);
            editText_input_account.setEnabled(false);
            UserManager.saveUserInfo(this, userEntity);
            //TODO 设置个人信息
            if (setAccountResult && setPhotoResult) {
                startActivity(new Intent(this, SetUserInfoActivity.class));
            }
        } else {
            setAccountResult = false;
            Toast.makeText(this, error, Toast.LENGTH_SHORT).show();
        }

    }

    @Override
    public void takeSuccess(final TResult result) {

        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                LogUtil.e("yjl", "takeSuccess:" + result.getImage().getCompressPath());
                if (result != null && result.getImage() != null) {
                    setPhotoResult = false;
                    photoPath = result.getImage().getCompressPath();
                    Bitmap bitmap = BitmapFactory.decodeFile(photoPath);
                    view_set_photo.setImageBitmap(bitmap);
                }
            }
        });

    }


    @Override
    public void takeFail(TResult result, String msg) {
        Log.i("yjl", "takeFail:" + msg);
    }

    @Override
    public void takeCancel() {
        Log.i("yjl", getResources().getString(R.string.msg_operation_canceled));
    }


    @Override
    public void updateSetPhotoView(String photoUrl) {
        if (!TextUtils.isEmpty(photoUrl)) {
            setPhotoResult = true;
            userEntity.mUserImage = photoUrl;
            UserManager.saveUserInfo(this, userEntity);
            if (setPhotoResult && setAccountResult) {
//                UserManager.saveUserInfo(this, userEntity);
                startActivity(new Intent(this, SetUserInfoActivity.class));
                this.finish();
            }
        }
    }

    @Override
    public void showErrorData(NetworkManager.ResultCode resultCode, String msg) {
        super.showErrorData(resultCode, msg);
    }

}
